<template>
  <view class="coupon-issue">
  

    <!-- 表单内容 -->
    <view class="form-content">
      <!-- 优惠券名称 -->
      <view class="form-item">
        <view class="form-label">优惠券名称</view>
        <input class="form-input" v-model="couponForm.name" placeholder="请输入优惠券名称" />
      </view>

      <!-- 优惠券类型 -->
      <view class="form-item">
        <view class="form-label">优惠券类型</view>
        <view class="tab-group">
          <view 
            class="tab-item" 
            :class="{ active: couponForm.type === 'discount' }"
            @click="couponForm.type = 'discount'"
          >
            <text>满减券</text>
          </view>
          <view 
            class="tab-item" 
            :class="{ active: couponForm.type === 'percentage' }"
            @click="couponForm.type = 'percentage'"
          >
            <text>打折券</text>
          </view>
        </view>
      </view>

      <!-- 满减券金额输入 -->
      <view v-if="couponForm.type === 'discount'" class="form-item">
        <view class="form-value">
          满<input class="form-input-small" v-model="couponForm.minSpend" type="number" placeholder="" />
          元减<input class="form-input-small" v-model="couponForm.discountAmount" type="number" placeholder="" />
          元
        </view>
      </view>

      <!-- 打折券折扣输入 -->
      <view v-if="couponForm.type === 'percentage'" class="form-item">
        <view class="form-value">
          打<input class="form-input-medium" v-model.number="couponForm.discountPercentage" type="number" placeholder="" />
          折
        <view v-if="Number(couponForm.discountPercentage) > 10 || Number(couponForm.discountPercentage) < 0">
          <text style="color: red; font-size: 24rpx;">折扣必须在0-10之间</text>
        </view>
        </view>
      </view>

      <!-- 发放开始时间 -->
      <view class="form-item">
        <view class="form-label">发放开始时间</view>
        <picker mode="date" :value="couponForm.startDate || ''" @change="(e: any) => onDateChange('startDate', e)">
          <view class="date-picker">
            <text class="date-text">{{ couponForm.startDate || '选择日期' }}</text>
            <text class="date-arrow"> > </text>
          </view>
        </picker>
      </view>

      <!-- 发放结束时间 -->
      <view class="form-item">
        <view class="form-label">发放结束时间</view>
        <picker mode="date" :value="couponForm.endDate || ''" @change="(e: any) => onDateChange('endDate', e)">
          <view class="date-picker">
            <text class="date-text">{{ couponForm.endDate || '选择日期' }}</text>
            <text class="date-arrow"> > </text>
          </view>
        </picker>
      </view>

      <!-- 投放数量 -->
      <view class="form-item">
        <view class="form-label">投放数量</view>
        <input class="form-input" v-model.number="couponForm.totalQuantity" type="number" placeholder="请输入投放数量" />
      </view>

      <!-- 每人限领 -->
      <view class="form-item">
        <view class="form-label">每人限领</view>
        <input class="form-input" v-model.number="couponForm.limitPerUser" type="number" placeholder="请输入每人限领数量" />
      </view>

      <!-- 使用有效期 -->
      <view class="form-item">
        <view class="form-label">使用有效期</view>
        <view class="validity-period">
          <picker mode="date" :value="couponForm.validStartDate || ''" @change="(e: any) => onDateChange('validStartDate', e)">
            <view class="date-btn">{{ couponForm.validStartDate || '开始时间' }}</view>
          </picker>
          <picker mode="date" :value="couponForm.validEndDate || ''" @change="(e: any) => onDateChange('validEndDate', e)">
            <view class="date-btn">{{ couponForm.validEndDate || '结束时间' }}</view>
          </picker>
        </view>
      </view>

      <!-- 确认投放按钮 -->
      <button class="submit-btn" @click="submitForm">确认投放</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';

// 在 uni-app 中，API 可以通过全局的 uni 对象访问
const showToast = uni.showToast;
const navigateBack = uni.navigateBack;

// 优惠券表单数据
const couponForm = reactive({
  name: '',
  type: 'discount', // discount: 满减券, percentage: 打折券
  minSpend: '',
  discountAmount: '',
  discountPercentage: '',
  startDate: '2025-11-19',
  endDate: '2025-11-20',
  totalQuantity: 0,
  limitPerUser: 0,
  validStartDate: '',
  validEndDate: ''
});

// 日期字段类型定义
type DateField = 'startDate' | 'endDate' | 'validStartDate' | 'validEndDate';

// 日期选择器结果类型
interface DatePickerSuccessResult {
  dateString: string;
}

// 处理日期变化
const onDateChange = (fieldName: DateField, e: any) => {
  console.log('日期选择变化，字段名:', fieldName, '选择值:', e.detail.value);
  
  try {
    // 更新表单数据
    couponForm[fieldName] = e.detail.value;
    
    // 显示成功提示
    showToast({
      title: '日期选择成功',
      icon: 'none'
    });
    
    console.log('日期设置成功:', fieldName, '=', e.detail.value);
  } catch (error) {
    console.error('日期设置异常:', error);
    showToast({
      title: '日期设置失败',
      icon: 'none'
    });
  }
};

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!couponForm.name) {
    showToast({
      title: '请输入优惠券名称',
      icon: 'none'
    });
    return;
  }

  if (couponForm.type === 'discount') {
    if (!couponForm.minSpend || !couponForm.discountAmount) {
      showToast({
        title: '请输入满减金额',
        icon: 'none'
      });
      return;
    }
  } else {
    if (!couponForm.discountPercentage) {
      showToast({
        title: '请输入折扣',
        icon: 'none'
      });
      return;
    }
  }

  if (!couponForm.totalQuantity || !couponForm.limitPerUser) {
    showToast({
      title: '请输入投放数量和每人限领数量',
      icon: 'none'
    });
    return;
  }

  if (!couponForm.startDate || !couponForm.endDate) {
    showToast({
      title: '请选择发放时间',
      icon: 'none'
    });
    return;
  }
  
  if (!couponForm.validStartDate || !couponForm.validEndDate) {
    showToast({
      title: '请选择使用有效期',
      icon: 'none'
    });
    return;
  }
  
  // 验证日期逻辑
  if (new Date(couponForm.startDate) > new Date(couponForm.endDate)) {
    showToast({
      title: '发放开始时间不能晚于结束时间',
      icon: 'none'
    });
    return;
  }
  
  if (new Date(couponForm.validStartDate) > new Date(couponForm.validEndDate)) {
    showToast({
      title: '使用开始时间不能晚于结束时间',
      icon: 'none'
    });
    return;
  }

  try {
    // 显示加载提示
    uni.showLoading({
      title: '正在投放中...',
      mask: true
    });
    
    // 计算lastTime：发放开始时间和结束时间之间的秒数差
    const startTime = new Date(couponForm.startDate).getTime();
    const endTime = new Date(couponForm.endDate).getTime();
    const lastTime = Math.floor((endTime - startTime) / 1000); // 转换为秒
    
    // 调用第一个POST接口
    console.log('开始调用第一个接口...');
    const res1 = await uni.request({
      url: 'http://localhost:8080/cc/merchant/create',
      method: 'POST',
      data: {
        name: couponForm.name,
        lastTime: lastTime,
        number: couponForm.totalQuantity
      },
      header: {
        'content-type': 'application/json'
      },
      timeout: 10000 // 设置10秒超时
    });
    
    if (res1.statusCode !== 200) {
      throw new Error(`创建优惠券基础信息失败: HTTP ${res1.statusCode}`);
    }
    
    // 检查响应数据是否成功 - 更安全的方式，支持code为200表示成功的格式
    const data1 = res1.data as { code?: number; message?: string } | null;
    if (!data1 || (data1.code !== undefined && data1.code !== 200)) {
      throw new Error(`创建优惠券基础信息失败: ${data1?.message || '接口返回错误'}`);
    }
    
    console.log('第一个接口调用成功:', data1);
    
    // 准备第二个接口的参数
    const type = couponForm.type === 'percentage' ? 0 : 1; // 0打折/1满减
    const discount = couponForm.type === 'percentage' 
      ? Number(couponForm.discountPercentage) / 10 // 转换为小数，如8折转0.8
      : undefined;
    
    // 调用第二个GET接口
    console.log('开始调用第二个接口...');
    const res2 = await uni.request({
      url: 'http://localhost:8080/cc/merchant/insertCoupon',
      method: 'GET',
      data: {
        name: couponForm.name,
        type: type,
        discount: discount,
        triggerMoney: couponForm.minSpend,
        preferentialMoney: couponForm.discountAmount,
        start: couponForm.startDate,
        end: couponForm.endDate,
        num: couponForm.totalQuantity,
        size: couponForm.limitPerUser,
        expirationStart: couponForm.validStartDate,
        expirationEnd: couponForm.validEndDate,
        status: 0
      },
      timeout: 10000 // 设置10秒超时
    });
    
    if (res2.statusCode !== 200) {
      throw new Error(`添加优惠券详情失败: HTTP ${res2.statusCode}`);
    }
    
    // 检查响应数据是否成功 - 更安全的方式，支持code为200表示成功的格式
    const data2 = res2.data as { code?: number; message?: string } | null;
    if (!data2 || (data2.code !== undefined && data2.code !== 200)) {
      throw new Error(`添加优惠券详情失败: ${data2?.message || '接口返回错误'}`);
    }
    
    console.log('第二个接口调用成功:', data2);
    
    // 隐藏加载提示
    uni.hideLoading();
    
    // 提交成功后返回上一页
    showToast({
      title: '优惠券投放成功！',
      icon: 'success',
      duration: 2000
    });

    // 模拟提交后返回
    setTimeout(() => {
      navigateBack();
    }, 2000);
  } catch (error) {
    // 隐藏加载提示
    uni.hideLoading();
    
    const errorMessage = error instanceof Error ? error.message : '投放失败，请重试';
    console.error('提交失败:', error);
    showToast({
      title: errorMessage,
      icon: 'none',
      duration: 3000
    });
  }
};
</script>

<style scoped lang="scss">
.coupon-issue {
  padding: 0 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;

    .title {
      font-size: 36rpx;
      font-weight: bold;
    }

    .header-actions {
      display: flex;
      gap: 20rpx;

      .icon {
        width: 24rpx;
        height: 24rpx;
        background-color: #333;
        border-radius: 50%;
      }
    }
  }

  .form-content {
    background-color: #fff;
    border-radius: 10rpx;
    padding: 30rpx;

    .form-item {
      margin-bottom: 30rpx;

      .form-label {
        font-size: 32rpx;
        color: #333;
        margin-bottom: 20rpx;
      }

      .form-input {
        width: 100%;
        height: 80rpx;
        border: 1rpx solid #ddd;
        border-radius: 6rpx;
        padding: 0 20rpx;
        box-sizing: border-box;
      }

      .form-input-small {
        width: 100rpx;
        height: 60rpx;
        border: 1rpx solid #ddd;
        border-radius: 6rpx;
        text-align: center;
      }

      .form-input-medium {
        width: 200rpx;
        height: 60rpx;
        border: 1rpx solid #ddd;
        border-radius: 6rpx;
        text-align: center;
      }

      .form-value {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        gap: 10rpx;
      }

      .tab-group {
        display: flex;
        gap: 20rpx;
        margin-top: 10rpx;
      }

      .tab-item {
        flex: 1;
        height: 70rpx;
        line-height: 70rpx;
        text-align: center;
        border: 1rpx solid #ddd;
        border-radius: 35rpx;
        background-color: #fff;
        transition: all 0.3s ease;

        &.active {
          background-color: #007aff;
          border-color: #007aff;

          text {
            color: #fff;
          }
        }

        text {
          font-size: 32rpx;
          color: #333;
          transition: color 0.3s ease;
        }
      }

      .date-picker {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 80rpx;
        border: 1rpx solid #ddd;
        border-radius: 6rpx;
        padding: 0 20rpx;
        box-sizing: border-box;

        .date-text {
          font-size: 32rpx;
          color: #333;
        }

        .date-arrow {
          font-size: 28rpx;
          color: #999;
        }
      }

      .validity-period {
        display: flex;
        gap: 20rpx;

        .date-btn {
          width: 300rpx;
          flex: 1;
          height: 80rpx;
          background-color: #fff;
          border: 1rpx solid #ddd;
          border-radius: 6rpx;
          color: #333;
          font-size: 32rpx;
          line-height: 80rpx;
          text-align: center;
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
          transition: all 0.3s ease;
          
          &:hover, &:active {
            border-color: #007aff;
            background-color: #f0f8ff;
          }
        }
      }
    }

    .submit-btn {
      width: 100%;
      height: 90rpx;
      background-color: #007aff;
      color: #fff;
      font-size: 36rpx;
      border-radius: 6rpx;
      margin-top: 40rpx;
    }
  }
}
</style>